package com.neu.events;

import com.neu.base.AuthContants;
import com.neu.entity.User;
import com.neu.entity.security.LoginUser;
import com.neu.service.AuthenticationService;
import com.neu.utils.JwtUtils;
import com.neu.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class UserUpdateListener {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private AuthenticationService authenticationService;

    @EventListener
    public void handleUserUpdateEvent(UserUpdateEvent event) {
        User user = event.getUser();
        String username = user.getUsername();
        // 获取最新的用户信息
        LoginUser loginUser = authenticationService.login(username);

        // 更新 Redis 中的用户信息
        redisUtil.set(AuthContants.REDIS_KEY_AUTH_USER_DETAIL + username, loginUser, jwtUtils.getExpiration());

        // 更新 SecurityContext 中的用户信息
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, loginUser.getPassword(), loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 你还可以做一些其他的操作，比如发出日志，或者更新缓存中的其他信息等
        log.info("用户 {} 的信息已经在Redis和SecurityContext更新！", username);
    }
}